import Vue from 'vue'
import Router from 'vue-router'
import vmain from '@/components/vmain'
import brandhouse from '@/components/brand/brandhouse'
import branddetail from '@/components/brand/branddetail'

import order from '@/components/order/order'
import fastorder from '@/components/fastorder/fastorder'
import login from '@/components/permission/login'
import forgetpassword from '@/components/permission/forgetpassword'
import register from '@/components/permission/register'
import myinfo from '@/components/about/myinfo'
import activity from '@/components/activity/activity'
import productdetail from '@/components/product/productdetail'
import myorder from '@/components/about/myorder'
import qa from '@/components/about/qa'
import cart from '@/components/cart/cart'

import topic from '@/components/topic/topic'
import topicdetail from '@/components/topic/topicdetail'

import store from '@/store/index'
Vue.use(Router)
const router =  new Router({
	routes: [{
			path: '/',
			name: 'vmain',
			component: vmain
		},
		{
			path: '/brandhouse',
			name: 'brandhouse',
			component: brandhouse
		},
		{
			path: '/branddetail',
			name: 'branddetail',
			component: branddetail
		},
		{
			path: '/order',
			name: 'order',
			component: order
		},
		{
			path: '/productdetail',
			name: 'productdetail',
			component: productdetail
		},
		{
			path: '/fastorder',
			name: 'fastorder',
			component: fastorder
		},
		{
			path: '/login',
			name: 'login',
			component: login
		},
		{
			path: '/forgetpassword',
			name: 'forgetpassword',
			component: forgetpassword
		},
		{
			path: '/register',
			name: 'register',
			component: register
		},
		{
			path: '/myinfo',
			name: 'myinfo',
			component: myinfo
		},
		{
			path: '/activity',
			name: 'activity',
			component: activity
		},
		{
			path: '/myorder',
			name: 'myorder',
			component: myorder
		},
		{
			path: '/cart',
			name: 'cart',
			meta: {
				requireAuth: true, // 添加该字段，表示进入这个路由是需要登录的
			},
			component: cart
		},
		{
			path: '/topic',
			name: 'topic',
			component: topic
		},
		{
			path: '/qa',
			name: 'qa',
			component: qa
		},
		{
			path: '/topicdetail',
			name: 'topicdetail',
			component: topicdetail
		}
	]
})
router.beforeEach((to, from, next) => {
    if (to.meta.requireAuth) {  // 判断该路由是否需要登录权限
        if (store.state.token) {  // 通过vuex state获取当前的token是否存在
            next();
        }
        else {
            next({
                path: '/login',
                query: {redirect: to.fullPath}  // 将跳转的路由path作为参数，登录成功后跳转到该路由
            })
        }
    }
    else {
        next();
    }
})

export default router
